<?php
/**
 * 案件控制器
 */

declare (strict_types = 1);

namespace app\controller\lawcase;

use app\BaseController;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;

class Lawcase extends BaseController
{
    /**
     * 查看案件列表
     */
    public function list()
    {
        // 修复参数获取问题：从 REQUEST_URI 中解析参数
        $requestUri = $_SERVER['REQUEST_URI'] ?? '';
        $param = [];
        
        if (strpos($requestUri, '?') !== false) {
            $urlParts = explode('?', $requestUri);
            if (isset($urlParts[1])) {
                parse_str($urlParts[1], $param);
            }
        }
        
        // 如果仍然没有参数，尝试使用 ThinkPHP 的方式
        if (empty($param)) {
            $param = Request::param();
        }        
        
        $page = isset($param['page']) ? intval($param['page']) : 1;
        $limit = isset($param['limit']) ? intval($param['limit']) : 10;
        
        $where[] = ['lc.delete_time', '=', '0'];

        // 数据权限过滤逻辑 - 最高优先级的过滤机制
        $userId = $this->getUserId();
        
        // 1. 获取用户所属部门ID
        $userDepartmentId = $this->getUserDepartmentId();
        
        // 2. 检查用户是否为律师（通过多种方式判断）
        $userInfo = Db::name('admin')->where('id', $userId)->find();
        
        // 判断是否为律师的条件：
        // - user_type == 2（外联律师）
        // - 或者 lawyer_id > 0（关联了律师信息）
        // - 或者在 oa_lawyer 表中存在该用户ID
        // - 或者所属部门名称包含“律师事务所”（内部律师）
        $isExternalLawyer = $userInfo && isset($userInfo['user_type']) && ($userInfo['user_type'] == 2);
        $hasLawyerLink = $userInfo && isset($userInfo['lawyer_id']) && ($userInfo['lawyer_id'] > 0);
        $isInLawyerTable = Db::name('lawyer')->where('admin_id', $userId)->count() > 0;
        
        // 检查是否为律所部门（部门名称包含“律师事务所”）
        $isLawFirmDept = false;
        if ($userDepartmentId > 0) {
            $deptName = Db::name('department')->where('id', $userDepartmentId)->value('title');
            $isLawFirmDept = $deptName && (strpos($deptName, '律师事务所') !== false);
        }
        
        // 律师身份判定：只要满足任何一个条件即为律师
        $isLawyer = $isExternalLawyer || $hasLawyerLink || $isInLawyerTable || $isLawFirmDept;
        
        // 3. 检查是否为法务中心员工（部门ID为17）
        $isLegalCenterStaff = ($userDepartmentId == 17);
        
        // 4. 检查是否为超级管理员（但律师身份优先）
        $isSuperAdmin = !$isLawyer && $this->checkSuperAdmin();
        
        // 根据不同角色设置不同的数据权限 - 最高级过滤
        // 注意：律师身份优先于超级管理员判断
        if (!$isSuperAdmin && !$isLegalCenterStaff) {
            if ($isLawyer) {
                // 律师只能看到自己主办的案件、作为管家的案件或作为出庭律师的案件
                $where[] = function($query) use ($userId) {
                    $query->where('lc.main_lawyer', '=', $userId)
                          ->whereOr('lc.secondary_lawyer', '=', $userId)
                          ->whereOr('lc.session_lawyer', '=', $userId);
                };
            } else {
                // 其他用户只能看到自己主办的案件
                $where[] = ['lc.main_lawyer', '=', $userId];
            }
        }
        
        // 搜索栏的条件 - 在最高级过滤之下的补充过滤条件
        
        // 按关键词搜索（案件编号、委托人、对方当事人）
        if (!empty($param['keywords'])) {
            $keywords = trim($param['keywords']);
            // 创建子查询用于搜索委托人和对方当事人
            $partySubQuery = Db::name('lawcase_party')
                ->alias('lp')
                ->join('party p', 'lp.party_id = p.id', 'LEFT')
                ->where('p.name', 'like', '%' . $keywords . '%')
                ->where('lp.delete_time', '=', 0)
                ->column('lp.case_id');
            
            // 如果找到了匹配的当事人，构建OR条件
            if (!empty($partySubQuery)) {
                $where[] = function($query) use ($keywords, $partySubQuery) {
                    $query->where('lc.case_code', 'like', '%' . $keywords . '%')
                          ->whereOr('lc.id', 'in', $partySubQuery);
                };
            } else {
                // 如果没有找到匹配的当事人，只搜索案件编号
                $where[] = ['lc.case_code', 'like', '%' . $keywords . '%'];
            }
        }
        
        // 按案件状态筛选
        if (!empty($param['status'])) {
            $where[] = ['lc.status', '=', $param['status']];
        }
        
        // 按案件类型筛选
        if (!empty($param['case_type'])) {
            $where[] = ['lc.case_type', '=', $param['case_type']];
        }
        
        // 按主办律师筛选 - 只有超级管理员和法务中心员工可以筛选其他律师的案件
        if (!empty($param['main_lawyer']) && ($isSuperAdmin || $isLegalCenterStaff)) {
            $where[] = ['lc.main_lawyer', '=', $param['main_lawyer']];
        }
        
        // 按管家（secondary_lawyer）筛选
        if (!empty($param['secondary_lawyer'])) {
            $where[] = ['lc.secondary_lawyer', '=', $param['secondary_lawyer']];
        }
        
        // 按出庭律师（session_lawyer）筛选
        if (!empty($param['session_lawyer'])) {
            $where[] = ['lc.session_lawyer', '=', $param['session_lawyer']];
        }
        
        // 按客户ID筛选（新增）
        if (!empty($param['customer_id'])) {
            $customerId = intval($param['customer_id']);
            // 先查询所有与该客户关联的当事人
            $partyIds = Db::name('party')
                ->where('customer_id', '=', $customerId)
                ->where('delete_time', '=', 0)
                ->column('id');
            
            if (!empty($partyIds)) {
                // 再查询所有与这些当事人关联的案件
                $caseIds = Db::name('lawcase_party')
                    ->where('party_id', 'in', $partyIds)
                    ->where('delete_time', '=', 0)
                    ->column('case_id');
                
                if (!empty($caseIds)) {
                    $where[] = ['lc.id', 'in', $caseIds];
                } else {
                    // 如果没有找到关联的案件，添加一个永远不满足的条件
                    $where[] = ['lc.id', '=', 0];
                }
            } else {
                // 如果没有找到关联的当事人，添加一个永远不满足的条件
                $where[] = ['lc.id', '=', 0];
            }
        }
        
        // 按接案日期筛选
        if (!empty($param['start_date']) && !empty($param['end_date'])) {
            $startDate = trim($param['start_date']);
            $endDate = trim($param['end_date']);
            
            // 确保日期格式正确 (YYYY-MM-DD)
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $startDate) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $endDate)) {
                $where[] = ['lc.entrust_date', 'between', [$startDate, $endDate]];
            }
        } else if (!empty($param['start_date'])) {
            $startDate = trim($param['start_date']);
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $startDate)) {
                $where[] = ['lc.entrust_date', '>=', $startDate];
            }
        } else if (!empty($param['end_date'])) {
            $endDate = trim($param['end_date']);
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $endDate)) {
                $where[] = ['lc.entrust_date', '<=', $endDate];
            }
        }
        
        // 按开庭日期筛选
        if (!empty($param['session_time_start']) && !empty($param['session_time_end'])) {
            $sessionTimeStart = trim($param['session_time_start']);
            $sessionTimeEnd = trim($param['session_time_end']);
            
            // 确保日期格式正确 (YYYY-MM-DD)
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $sessionTimeStart) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $sessionTimeEnd)) {
                // 将日期转换为时间戳进行比较
                $startTime = strtotime($sessionTimeStart);
                $endTime = strtotime($sessionTimeEnd . ' 23:59:59'); // 包含整天
                $where[] = ['lc.session_time', 'between', [$startTime, $endTime]];
            }
        } else if (!empty($param['session_time_start'])) {
            $sessionTimeStart = trim($param['session_time_start']);
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $sessionTimeStart)) {
                $startTime = strtotime($sessionTimeStart);
                $where[] = ['lc.session_time', '>=', $startTime];
            }
        } else if (!empty($param['session_time_end'])) {
            $sessionTimeEnd = trim($param['session_time_end']);
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $sessionTimeEnd)) {
                $endTime = strtotime($sessionTimeEnd . ' 23:59:59');
                $where[] = ['lc.session_time', '<=', $endTime];
            }
        }
        
        // 按挂起状态筛选
        if (isset($param['is_suspended']) && $param['is_suspended'] !== '') {
            $where[] = ['lc.is_suspended', '=', $param['is_suspended']];
        }        
        
        // 权限控制已经在前面的代码中完成
        // 现在$where数组包含了所有的过滤条件：
        // 1. 最高级的权限过滤条件
        // 2. 搜索栏的补充过滤条件（如关键词、状态、类型、律师筛选等）
        
        try {
            
            // 查询案件列表
            $list = Db::name('lawcase')
                ->alias('lc')
                ->join('admin a1', 'lc.main_lawyer = a1.id', 'LEFT')
                ->join('admin a2', 'lc.secondary_lawyer = a2.id', 'LEFT')
                ->join('admin a3', 'lc.session_lawyer = a3.id', 'LEFT')
                ->join('court lcrt', 'lc.court_id = lcrt.id', 'LEFT')
                ->join('case_cause lccc', 'lc.case_cause_id = lccc.id', 'LEFT')
                ->join('lawcase_party lcp', 'lcp.case_id = lc.id AND lcp.is_client = 1', 'LEFT')
                ->join('party p', 'lcp.party_id = p.id', 'LEFT')
                ->field('lc.*, a1.name as main_lawyer_name, a2.name as secondary_lawyer_name, a3.name as session_lawyer_name, lcrt.name as court_name, lccc.name as case_cause_name')
                ->where($where)
                ->page($page, $limit)
                ->order('lc.id', 'desc')
                ->group('lc.id')
                ->select()
                ->each(function($item) {
                    // 格式化时间
                    $item['create_time'] = $item['create_time'] ?  $item['create_time'] : '';
                    $item['update_time'] = $item['update_time'] ? $item['update_time'] : '';
                    $item['session_time'] = $item['session_time'] ? $item['session_time'] : '';
                      
                    // 诉讼地位名称映射
                    $relationshipNames = [
                        '1' => '原告',
                        '2' => '被告',
                        '3' => '第三人'
                    ];
                      
                    // 获取委托人信息
                    $clients = Db::name('lawcase_party')
                        ->alias('lp')
                        ->join('party p', 'lp.party_id = p.id', 'LEFT')
                        ->where([
                            ['lp.case_id', '=', $item['id']],
                            ['lp.is_client', '=', 1],
                            ['lp.delete_time', '=', 0]
                        ])
                        ->field('p.name, lp.relationship')
                        ->select();
                      
                    // 处理委托人信息，添加诉讼地位
                    $clientInfos = [];
                    $opponentInfos = [];
                    foreach ($clients as $client) {
                        $relationshipKey = (string)$client['relationship'];
                        $relationshipName = $relationshipNames[$relationshipKey] ?? '';
                        $clientInfos[] = $client['name'] . ($relationshipName ? '(' . $relationshipName . ')' : '');
                    }
                    
                    // 获取对方当事人信息
                    $opponents = Db::name('lawcase_party')
                        ->alias('lp')
                        ->join('party p', 'lp.party_id = p.id', 'LEFT')
                        ->where([
                            ['lp.case_id', '=', $item['id']],
                            ['lp.is_client', '=', 2],
                            ['lp.delete_time', '=', 0]
                        ])
                        ->field('p.name, lp.relationship')
                        ->select();
                    
                    // 确保结果是数组格式
                    if (is_object($opponents)) {
                        $opponents = $opponents->toArray();
                    } elseif (!is_array($opponents)) {
                        $opponents = [];
                    }
                       
                    // 处理对方当事人信息，添加诉讼地位
                    foreach ($opponents as $opponent) {
                        $relationshipKey = (string)$opponent['relationship'];
                        $relationshipName = $relationshipNames[$relationshipKey] ?? '';
                        $opponentInfos[] = $opponent['name'] . ($relationshipName ? '(' . $relationshipName . ')' : '');
                    }
                    
                    $item['clients'] = implode('、', $clientInfos);
                    $item['opponents'] = implode('、', $opponentInfos);
                    // 同时填充client_info和opponent_info字段，以兼容前端类型定义
                    $item['client_info'] = $item['clients'];
                    $item['opponent_info'] = $item['opponents'];
                    
                    // 案件状态名称映射
                    $statusNames = [
                        '准备阶段（未提交立案）' => '准备阶段',
                        '起诉阶段（提交立案待受理）' => '起诉阶段',
                        '庭前阶段（立案受理未开庭）' => '庭前阶段',
                        '审判阶段（已开庭未出判决）' => '审判阶段',
                        '庭后阶段（已判决未生效）' => '庭后阶段',
                        '执行阶段（判决生效）' => '执行阶段',
                        '撤诉' => '已撤诉',
                        '终止委托' => '已终止',
                        '结案' => '已结案',
                        '0' => '进行中',
                        '1' => '已归档',
                        '2' => '已结案'
                    ];
                    
                    $item['status_text'] = $statusNames[$item['status']] ?? $item['status'];
                    
                    // 案件类型名称映射
                    $caseTypeNames = [
                        '民事' => '民事案件',
                        '刑事' => '刑事案件',
                        '行政' => '行政案件',
                        '0' => '诉讼类',
                        '1' => '非诉讼类'
                    ];
                    
                    $item['case_type_text'] = $caseTypeNames[$item['case_type']] ?? $item['case_type'];
                    
                    return $item;
                });
                
                // 查询案件总数
                $total = Db::name('lawcase')
                    ->alias('lc')
                    ->join('admin a1', 'lc.main_lawyer = a1.id', 'LEFT')
                    ->join('admin a2', 'lc.secondary_lawyer = a2.id', 'LEFT')
                    ->join('admin a3', 'lc.session_lawyer = a3.id', 'LEFT')
                    ->join('court lcrt', 'lc.court_id = lcrt.id', 'LEFT')
                    ->join('case_cause lccc', 'lc.case_cause_id = lccc.id', 'LEFT')
                    ->join('lawcase_party lcp', 'lcp.case_id = lc.id AND lcp.is_client = 1', 'LEFT')
                    ->join('party p', 'lcp.party_id = p.id', 'LEFT')
                    ->where($where)
                    ->count('lc.id');
                
                // 准备返回数据
        $data = [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $data, 'timestamp' => time()]);
            } catch (\Exception $e) {
                // 记录错误日志
                Log::error('查询案件列表失败: ' . $e->getMessage());
                return json(['code' => 500, 'msg' => '查询失败，请稍后重试']);
            }
        }

    
        /**
     * 查看单个案件信息
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            $lawcase = Db::name('lawcase')
                ->alias('lc')
                ->join('admin a1', 'lc.main_lawyer = a1.id', 'LEFT')
                ->join('admin a2', 'lc.secondary_lawyer = a2.id', 'LEFT')
                ->join('admin a3', 'lc.session_lawyer = a3.id', 'LEFT')
                ->join('court lcrt', 'lc.court_id = lcrt.id', 'LEFT')
                ->join('case_cause lccc', 'lc.case_cause_id = lccc.id', 'LEFT')
                ->field('lc.*, a1.name as main_lawyer_name, a2.name as secondary_lawyer_name, a3.name as session_lawyer_name, lcrt.name as court_name, lccc.name as case_cause_name')
                ->where('lc.id', $param['id'])
                ->find();
            
            if (empty($lawcase)) {
                return json(['code' => 404, 'msg' => '案件不存在']);
            }
            
            // 格式化时间
            $lawcase['create_time'] = $lawcase['create_time'] ? $lawcase['create_time'] : '';
            $lawcase['update_time'] = $lawcase['update_time'] ? $lawcase['update_time'] : '';
            $lawcase['session_time'] = $lawcase['session_time'] ? $lawcase['session_time'] : '';
            $lawcase['entrust_date'] = $lawcase['entrust_date'] ?? '';
            
            // 新增：获取开庭处所名称
            $sessionCourtName = Db::name('court')->where('id', $lawcase['session_court_id'])->value('name');
            $lawcase['session_court_name'] = $sessionCourtName ? $sessionCourtName : '';

            // 获取附件信息
            if (!empty($lawcase['file_ids'])) {
                $fileArray = Db::name('file')
                    ->where('id', 'in', explode(',', $lawcase['file_ids']))
                    ->select();
                $lawcase['file_array'] = $fileArray;
            }
            
            // 诉讼地位名称映射
            $relationshipNames = [
                '1' => '原告',
                '2' => '被告',
                '3' => '第三人'
            ];
            
            // 新增：获取开庭处所名称
            $sessionCourtName = Db::name('court')->where('id', $lawcase['session_court_id'])->value('name');
            $lawcase['session_court_name'] = $sessionCourtName ? $sessionCourtName : '';
            
            // 获取委托人信息
            $clients = Db::name('lawcase_party')
                ->alias('lp')
                ->join('party p', 'lp.party_id = p.id', 'LEFT')
                ->where([
                    ['lp.case_id', '=', $lawcase['id']],
                    ['lp.is_client', '=', 1],
                    ['lp.delete_time', '=', 0]
                ])
                ->field('p.name, lp.relationship')
                ->select();
            
            // 处理委托人信息，添加诉讼地位
            $clientInfos = [];
            // 确保结果是数组格式
            if (is_object($clients)) {
                $clients = $clients->toArray();
            } elseif (!is_array($clients)) {
                $clients = [];
            }
            foreach ($clients as $client) {
                $relationshipKey = (string)$client['relationship'];
                $relationshipName = isset($relationshipNames[$relationshipKey]) ? $relationshipNames[$relationshipKey] : '未知';
                $clientInfos[] = $client['name'] . '（' . $relationshipName . '）';
            }
            $lawcase['party_names'] = $clientInfos;
            
            // 获取对方当事人信息
            $opponents = Db::name('lawcase_party')
                ->alias('lp')
                ->join('party p', 'lp.party_id = p.id', 'LEFT')
                ->where([
                    ['lp.case_id', '=', $lawcase['id']],
                    ['lp.is_client', '=', 2],
                    ['lp.delete_time', '=', 0]
                ])
                ->field('p.name, lp.relationship')
                ->select();
            
            // 确保结果是数组格式
            if (is_object($opponents)) {
                $opponents = $opponents->toArray();
            } elseif (!is_array($opponents)) {
                $opponents = [];
            }
            
            // 处理对方当事人信息，添加诉讼地位
            $opponentInfos = [];
            foreach ($opponents as $opponent) {
                $relationshipKey = (string)$opponent['relationship'];
                $relationshipName = isset($relationshipNames[$relationshipKey]) ? $relationshipNames[$relationshipKey] : '未知';
                $opponentInfos[] = $opponent['name'] . '（' . $relationshipName . '）';
            }
            $lawcase['opposite_party_names'] = $opponentInfos;
            
            // 添加案件类型和案由信息
            $lawcase['case_type_text'] = $this->getCaseTypeText($lawcase['case_type']);
            $lawcase['case_cause_text'] = $lawcase['case_cause_name'];
            
            // 获取委托人客户信息及会员状态
            $lawcase['client_membership_info'] = [];
            try {
                // 查询委托人信息（使用type=1作为委托人标识）
                $clientInfo = Db::name('lawcase_party')
                    ->alias('lp')
                    ->join('party p', 'lp.party_id = p.id', 'LEFT')
                    ->where(['lp.case_id' => $param['id'], 'lp.type' => 1, 'lp.delete_time' => 0])
                    ->field('p.customer_id')
                    ->find();
                    
                if ($clientInfo && !empty($clientInfo['customer_id'])) {
                    // 直接查询客户表获取会员信息（使用与客户详情API相同的字段）
                    $customerInfo = Db::name('customer')
                        ->where(['id' => $clientInfo['customer_id']])
                        ->field('id as customer_id, status as customer_status, level as customer_level, type as customer_type, is_member, membership_end_time, manager_id')
                        ->find();
                        
                    if ($customerInfo) {
                        // 获取会员状态名称
                        $statusName = '';
                        if ($customerInfo['customer_status'] !== null && $customerInfo['customer_status'] !== '') {
                            $statusConfig = Db::name('basic_customer')
                                ->where('type', 'customer_status')
                                ->where('value', $customerInfo['customer_status'])
                                ->value('name');
                            $statusName = $statusConfig ?: '';
                        }
                        
                        // 获取客户类型名称
                        $typeName = '';
                        if ($customerInfo['customer_type'] !== null && $customerInfo['customer_type'] !== '') {
                            $typeConfig = Db::name('basic_customer')
                                ->where('type', 'customer_type')
                                ->where('value', $customerInfo['customer_type'])
                                ->value('name');
                            $typeName = $typeConfig ?: '';
                        }
                        
                        // 获取客户等级名称
                        $levelName = '';
                        if ($customerInfo['customer_level'] !== null && $customerInfo['customer_level'] !== '') {
                            $levelConfig = Db::name('basic_customer')
                                ->where('type', 'customer_level')
                                ->where('value', $customerInfo['customer_level'])
                                ->value('name');
                            $levelName = $levelConfig ?: '';
                        }
                        
                        // 获取管家信息
                        $managerName = Db::name('user')
                            ->where(['id' => $customerInfo['manager_id']])
                            ->value('name') ?: '未分配';
                        
                        $lawcase['client_membership_info'] = [
                            'customer_id' => $customerInfo['customer_id'],
                            'customer_status' => $customerInfo['customer_status'],
                            'customer_status_name' => $statusName ?: '未设置',
                            'customer_level' => $customerInfo['customer_level'],
                            'customer_level_name' => $levelName ?: '未设置',
                            'customer_type' => $customerInfo['customer_type'],
                            'customer_type_name' => $typeName ?: '未设置',
                            'is_member' => $customerInfo['is_member'],
                            'membership_end_time' => $customerInfo['membership_end_time'],
                            'manager_id' => $customerInfo['manager_id'] ?: 0,
                            'manager_name' => $managerName
                        ];
                    }
                }
            } catch (\Exception $e) {
                // 如果查询失败，记录错误但不影响主流程
                Log::record('获取案件客户会员信息失败: ' . $e->getMessage(), 'error');
                $lawcase['client_membership_info'] = [];
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $lawcase
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 获取案件类型文本
     */
    private function getCaseTypeText($caseType)
    {
        $types = [
            1 => '民事',
            2 => '刑事',
            3 => '行政'
        ];
        return $types[$caseType] ?? '未知类型';
    }

    
    /**
     * 新增案件
     */
    public function add()
    {
        $param = Request::param();
        
        // 动态生成案件编号，除非用户提供了自定义编号
        $caseCode = $param['case_code'] ?? $this->generateCaseCode($param['case_type'] ?? '');
        
        // 处理开庭时间
        $sessionTime = 0;
        if (!empty($param['session_time'])) {
            // 如果session_time已经是时间戳（整数），直接使用；否则转换为时间戳
            if (is_numeric($param['session_time'])) {
                $sessionTime = (int)$param['session_time'];
            } else {
                $sessionTime = strtotime($param['session_time']);
            }
        }
        
        $data = [
            'case_code' => $caseCode,
            'contract_id' => $param['contract_id'] ?? 0, // 支持从合同创建案件
            'case_type' => $param['case_type'] ?? '',
            'case_cause_id' => $param['case_cause_id'] ?? 0,
            'court_id' => $param['court_id'] ?? 0,
            'main_lawyer' => $param['main_lawyer'] ?? 0,
            'secondary_lawyer' => $param['manager'] ?? 0,
            'session_lawyer' => $param['session_lawyer'] ?? 0,
            'description' => $param['description'] ?? '',
            'session_time' => $sessionTime,
            'status' => $param['status'] ?? '准备阶段（未提交立案）',
            'stage' => $param['stage'] ?? '准备阶段',
            'entrust_date' => $param['entrust_date'] ?? date('Y-m-d'),
            // 兼容前端使用court_session_place字段，优先使用该字段的值
            'session_court_id' => $param['court_session_place'] ?? $param['session_court_id'] ?? 0,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            $caseId = Db::name('lawcase')->insertGetId($data);
            
            // 如果提供了合同ID，自动关联合同
            if (!empty($param['contract_id'])) {
                $this->link_contract_auto($caseId, $param['contract_id']);
            }
            
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $caseId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 自动关联合同（内部方法）
     */
    protected function link_contract_auto($caseId, $contractId)
    {
        try {
            // 检查合同是否存在
            $contractExists = Db::name('contract')->where('id', $contractId)->count();
            if (!$contractExists) {
                return false;
            }

            // 更新案件的合同ID
            Db::name('lawcase')
                ->where('id', $caseId)
                ->update([
                    'contract_id' => $contractId,
                    'update_time' => time()
                ]);

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 编辑案件
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 注释掉主办律师的验证，允许主办律师为空
        // 对于编辑操作，主办律师可以不传或者传0，表示不修改主办律师
        // 只有当传递了主办律师且值不为空时才进行验证
        /*if (isset($param['main_lawyer']) && $param['main_lawyer'] !== '' && $param['main_lawyer'] !== null) {
            if (empty($param['main_lawyer'])) {
                return json(['code' => 400, 'msg' => '主办律师不能为空']);
            }
        }*/
        
        // 获取案件原始数据，用于检测律师变更
        $originalCase = Db::name('lawcase')->where('id', $param['id'])->find();
        if (!$originalCase) {
            return json(['code' => 404, 'msg' => '案件不存在']);
        }
        
        // 处理开庭时间
        $sessionTime = 0;
        if (!empty($param['session_time'])) {
            // 如果session_time已经是时间戳（整数），直接使用；否则转换为时间戳
            if (is_numeric($param['session_time'])) {
                $sessionTime = (int)$param['session_time'];
            } else {
                $sessionTime = strtotime($param['session_time']);
            }
        }
        
        // 处理主办律师清空逻辑
        $mainLawyer = null;
        if (isset($param['main_lawyer'])) {
            // 如果传递了main_lawyer参数
            if ($param['main_lawyer'] === '' || $param['main_lawyer'] === null || $param['main_lawyer'] == 0) {
                // 清空主办律师
                $mainLawyer = 0;
            } else {
                // 设置主办律师
                $mainLawyer = $param['main_lawyer'];
            }
        }
        
        // 处理管家清空逻辑
        $secondaryLawyer = 0;
        if (isset($param['manager'])) {
            // 如果传递了manager参数
            if ($param['manager'] === '' || $param['manager'] === null || $param['manager'] == 0) {
                // 清空管家
                $secondaryLawyer = 0;
            } else {
                // 设置管家
                $secondaryLawyer = $param['manager'];
            }
        }
        
        // 处理出庭律师清空逻辑
        $sessionLawyer = null;
        if (isset($param['session_lawyer'])) {
            // 如果传递了session_lawyer参数
            if ($param['session_lawyer'] === '' || $param['session_lawyer'] === null || $param['session_lawyer'] == 0) {
                // 清空出庭律师
                $sessionLawyer = 0;
            } else {
                // 设置出庭律师
                $sessionLawyer = $param['session_lawyer'];
            }
        }
        
        $data = [
            'id' => $param['id'],
            'case_code' => $param['case_code'] ?? '',
            'case_type' => $param['case_type'] ?? '',
            'case_cause_id' => $param['case_cause_id'] ?? 0,
            'court_id' => $param['court_id'] ?? 0,
            'description' => $param['description'] ?? '',
            'session_time' => $sessionTime,
            'status' => $param['status'] ?? 1,
            'stage' => $param['stage'] ?? 1,
            // 兼容前端使用court_session_place字段，优先使用该字段的值
            'session_court_id' => $param['court_session_place'] ?? $param['session_court_id'] ?? 0,
            'update_time' => time()
        ];
        
        // 分别处理律师字段，确保null不被添加到更新数组中
        if (!is_null($mainLawyer)) {
            $data['main_lawyer'] = $mainLawyer;
        }
        if (!is_null($secondaryLawyer)) {
            $data['secondary_lawyer'] = $secondaryLawyer;
        }
        if (!is_null($sessionLawyer)) {
            $data['session_lawyer'] = $sessionLawyer;
        }
        
        // 移除数组中的null值，避免更新不需要更新的字段
        foreach ($data as $key => $value) {
            if (is_null($value)) {
                unset($data[$key]);
            }
        }
        
        // 如果主办律师被清空，需要删除oa_lawcase_lawyer表中的相关记录
        if (isset($param['main_lawyer']) && ($param['main_lawyer'] === '' || $param['main_lawyer'] === null || $param['main_lawyer'] == 0)) {
            Db::name('lawcase_lawyer')
                ->where('case_id', $param['id'])
                ->where('is_main', 1)
                ->update(['delete_time' => time()]);
        }
        
        try {
            // 开启事务，确保数据一致性
            Db::startTrans();
            
            // 更新案件信息
            Db::name('lawcase')->update($data);
            
            // 检测主办律师变更并生成进度记录
            if (!is_null($mainLawyer) && $mainLawyer != $originalCase['main_lawyer']) {
                $this->createLawyerChangeProgress(
                    $param['id'],
                    '主办律师',
                    $originalCase['main_lawyer'],
                    $mainLawyer
                );
                
                // 如果设置了新的主办律师，在lawcase_lawyer表中创建关联记录
                if ($mainLawyer > 0) {
                    // 先获取律师信息，包括律所ID
                    $lawyerInfo = Db::name('admin')->where('id', $mainLawyer)->find();
                    $lawfirmId = $lawyerInfo['did'] ?? 0;
                    
                    // 在lawcase_lawyer表中创建新的关联记录
                    Db::name('lawcase_lawyer')->insert([
                        'case_id' => $param['id'],
                        'lawyer_id' => $mainLawyer,
                        'lawfirm_id' => $lawfirmId,
                        'is_main' => 1, // 标记为主办律师
                        'create_time' => time(),
                        'update_time' => time()
                    ]);
                }
            }
            
            // 检测出庭律师变更并生成进度记录
            if (!is_null($sessionLawyer) && $sessionLawyer != $originalCase['session_lawyer']) {
                $this->createLawyerChangeProgress(
                    $param['id'],
                    '出庭律师',
                    $originalCase['session_lawyer'],
                    $sessionLawyer
                );
            }
            
            // 提交事务
            Db::commit();
            
            return json(['code' => 0, 'msg' => '编辑成功', 'data' => []]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500, 'msg' => '编辑失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除案件（软删除）
     */
    public function del()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            Db::name('lawcase')
                ->where('id', $param['id'])
                ->update([
                    'delete_time' => time(),
                    'update_time' => time()
                ]);
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 生成案件编号
     * 
     * @param string $caseType 案件类型
     * @return string
     */
    protected function generateCaseCode($caseType)
    {
        // 生成案件编号的逻辑
        // 案号规则：年份+类型+序号
        // 例如：根据当前日期生成案件编号前缀，然后加上随机数
        
        // 使用统一的时间基准
        $year = date('Y');
        $month = date('m');
        
        // 获取$case_type的第一个字，例如：民、刑、商、行政
        $caseTypePrefix = mb_substr($caseType, 0, 1, 'UTF-8');
        
        // 生成随机序号
        $random = rand(1000, 9999);
        
        return "{$year}（{$caseTypePrefix}）{$month}{$random}";
    }
    
    /**
     * 获取所有在职律师列表
     * @return \think\response\Json
     */
    public function get_all_lawyers()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 15);

        try {
            // 首先尝试查询分配到事务所部门的用户
            $query = Db::name('admin')
                ->alias('a')
                ->field('a.id as lawyer_id, a.name as lawyer_name, a.did as lawfirm_id, d.title as lawfirm_name')
                ->join('department d', 'd.id = a.did', 'left')
                ->where('a.status', 1)
                ->where('d.title', 'like', '%事务所%')
                ->order('a.id desc');
            
            $total = $query->count();
            $list = $query->page($page, $limit)->select();
            
            // 如果没有分配到事务所部门的用户，则查询法务相关部门的用户
            if ($total === 0) {
                $query = Db::name('admin')
                    ->alias('a')
                    ->field('a.id as lawyer_id, a.name as lawyer_name, a.did as lawfirm_id, d.title as lawfirm_name')
                    ->join('department d', 'd.id = a.did', 'left')
                    ->where('a.status', 1)
                    ->where(function($query) {
                        $query->where('d.title', 'like', '%法务%')
                              ->whereOr('d.title', 'like', '%律师%')
                              ->whereOr('d.title', 'like', '%律司%');
                    })
                    ->order('a.id desc');
                
                $total = $query->count();
                $list = $query->page($page, $limit)->select();
            }
            
            return json([
                'code' => 0,
                'msg' => '',
                'totalRow' => ['total' => $total],
                'count' => $total,
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取案件关联律师列表
     * @return \think\response\Json
     */
    public function get_lawyers()
    {
        $caseId = input('case_id/d', 0);
        $page = input('page/d', 1);
        $limit = input('limit/d', 15);

        if (empty($caseId)) {
            return json(['code' => 400, 'msg' => '参数错误', 'data' => []]);
        }

        try {
            $query = Db::name('lawcase_lawyer')
                ->where('case_id', $caseId)
                ->where('delete_time', 0);

            $total = $query->count();
            $list = $query->page($page, $limit)->select();

            return json([
                'code' => 0,
                'msg' => '',
                'totalRow' => ['total' => $total],
                'count' => $total,
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取案件关联当事人列表
     * @return \think\response\Json
     */
    public function get_case_parties()
    {
        $caseId = input('case_id/d', 0);
        $page = input('page/d', 1);
        $limit = input('limit/d', 15);

        if (empty($caseId)) {
            return json(['code' => 400, 'msg' => '参数错误', 'data' => []]);
        }

        try {
            $query = Db::name('lawcase_party')
                ->alias('lp')
                ->join('party p', 'p.id = lp.party_id')
                ->field([
                    'lp.*',
                    'p.name as partyName',
                    'p.party_type as partyType',
                    'p.id_number as idNumber',
                    'p.contact as contactPerson',
                    'p.phone as contactPhone'
                ])
                ->where('lp.case_id', $caseId)
                ->where('lp.delete_time', 0);  // 添加这行来过滤已删除的记录

            $total = $query->count();
            
            $list = $query->page($page, $limit)->select()->each(function($item) {
                // 委托身份文本映射
                $roleTypes = [
                    1 => '委托人',
                    2 => '对方当事人',
                    3 => '第三人'
                ];
                $item['is_client_text'] = isset($roleTypes[$item['is_client']]) ? $roleTypes[$item['is_client']] : '未知角色';
                
                // 诉讼地位文本映射
                $partyTypes = [
                    0 => '未知',
                    1 => '原告',
                    2 => '被告',
                    3 => '第三人',
                    4 => '上诉人',
                    5 => '被上诉人',
                    6 => '再审申请人',
                    7 => '再审被申请人',
                    8 => '执行人',
                    9 => '被执行人'
                ];
                $item['relationship_text'] = isset($partyTypes[$item['relationship']]) ? $partyTypes[$item['relationship']] : '未知';
                
                return $item;
            });

            return json([
                'code' => 0,
                'msg' => '',
                'totalRow' => ['total' => $total],
                'count' => $total,
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 获取案件关联的合同信息
     * @return \think\response\Json
     */
    public function get_related_contract()
    {
        $param = Request::param();
        $caseId = $param['case_id'] ?? 0;

        if (empty($caseId)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        try {
            $contractId = Db::name('lawcase')->where('id', $caseId)->value('contract_id');
            
            if (empty($contractId)) {
                return json(['code' => 0, 'msg' => 'success', 'data' => null]);
            }

            $contract = Db::name('contract')
                ->field('id, code, customer, sign_time')
                ->where('id', $contractId)
                ->find();

            if ($contract) {
                $contract['sign_time'] = $contract['sign_time'] ? date('Y-m-d', $contract['sign_time']) : '';
            }

            return json(['code' => 0, 'msg' => 'success', 'data' => $contract]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 获取可关联的合同列表
     * @return \think\response\Json
     */
    public function get_available_contracts()
    {
        $param = Request::param();
        $page = isset($param['page']) ? (int)$param['page'] : 1;
        $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
        $keywords = isset($param['keywords']) ? trim($param['keywords']) : '';

        try {
            $where = [];
            $where[] = ['delete_time', '=', 0];
            $where[] = ['archive_time', '=', 0];
            $where[] = ['void_time', '=', 0];

            // 关键词搜索
            if (!empty($keywords)) {
                $where[] = ['customer|code', 'like', '%' . $keywords . '%'];
            }

            $list = Db::name('contract')
                ->field('id, code, customer, sign_time, cost')
                ->where($where)
                ->page($page, $limit)
                ->order('id', 'desc')
                ->select()
                ->each(function($item) {
                    $item['sign_time'] = $item['sign_time'] ? date('Y-m-d', $item['sign_time']) : '';
                    // 格式化金额显示，确保传入的是数值类型
                    $item['cost'] = $item['cost'] ? number_format((float)$item['cost'], 2) : '0.00';
                    return $item;
                });

            $count = Db::name('contract')
                ->where($where)
                ->count();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'data' => $list,
                    'total' => $count
                ],
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 关联案件与合同
     * @return \think\response\Json
     */
    public function link_contract()
    {
        $param = Request::param();
        $caseId = $param['case_id'] ?? 0;
        $contractId = $param['contract_id'] ?? 0;

        // 参数验证
        if (empty($caseId) || empty($contractId)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        try {
            // 检查案件是否存在
            $caseExists = Db::name('lawcase')->where('id', $caseId)->count();
            if (!$caseExists) {
                return json(['code' => 400, 'msg' => '案件不存在']);
            }

            // 检查合同是否存在
            $contractExists = Db::name('contract')->where('id', $contractId)->count();
            if (!$contractExists) {
                return json(['code' => 400, 'msg' => '合同不存在']);
            }

            // 更新案件的合同ID
            Db::name('lawcase')
                ->where('id', $caseId)
                ->update([
                    'contract_id' => $contractId,
                    'update_time' => time()
                ]);

            return json(['code' => 0, 'msg' => '关联合同成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '关联合同失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 取消案件与合同的关联
     * @return \think\response\Json
     */
    public function unlink_contract()
    {
        $param = Request::param();
        $caseId = $param['case_id'] ?? 0;

        if (empty($caseId)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        try {
            // 检查案件是否存在
            $caseExists = Db::name('lawcase')->where('id', $caseId)->count();
            if (!$caseExists) {
                return json(['code' => 400, 'msg' => '案件不存在']);
            }

            // 更新案件的合同ID为0
            Db::name('lawcase')
                ->where('id', $caseId)
                ->update([
                    'contract_id' => 0,
                    'update_time' => time()
                ]);

            return json(['code' => 0, 'msg' => '取消关联合同成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '取消关联合同失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 创建律师变更进度记录
     * 
     * @param int $caseId 案件ID
     * @param string $lawyerType 律师类型（主办律师/出庭律师）
     * @param int $oldLawyerId 原律师ID
     * @param int $newLawyerId 新律师ID
     * @return void
     */
    protected function createLawyerChangeProgress($caseId, $lawyerType, $oldLawyerId, $newLawyerId)
    {
        try {
            // 获取律师姓名
            $oldLawyerName = '无';
            if ($oldLawyerId > 0) {
                $oldLawyer = Db::name('admin')->where('id', $oldLawyerId)->find();
                $oldLawyerName = $oldLawyer ? $oldLawyer['name'] : '未知律师';
            }
            
            $newLawyerName = '无';
            if ($newLawyerId > 0) {
                $newLawyer = Db::name('admin')->where('id', $newLawyerId)->find();
                $newLawyerName = $newLawyer ? $newLawyer['name'] : '未知律师';
            }
            
            // 生成进度内容，使用HTML格式突出显示变更前后的律师名字
            // 修改前：红色粗体，修改后：绿色粗体
            $content = "{$lawyerType}由 <span style='color: #f56c6c; font-weight: bold;'>{$oldLawyerName}</span> 变更为 <span style='color: #67c23a; font-weight: bold;'>{$newLawyerName}</span>";
            
            // 获取当前操作人ID
            $operatorId = $this->getUserId();
            
            // 插入进度记录
            $progressData = [
                'case_id' => $caseId,
                'event_type' => '其他',
                'event_time' => date('Y-m-d'),
                'content' => $content,
                'operator' => $operatorId,
                'create_time' => time(),
                'update_time' => time()
            ];
            
            Db::name('lawcase_progress')->insert($progressData);
            
            Log::info('律师变更进度记录已创建', [
                'case_id' => $caseId,
                'lawyer_type' => $lawyerType,
                'old_lawyer' => $oldLawyerName,
                'new_lawyer' => $newLawyerName
            ]);
        } catch (\Exception $e) {
            // 记录错误日志，但不影响主流程
            Log::error('创建律师变更进度记录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取案件开庭时间表
     * @return \think\response\Json
     */
    public function court_schedule_list()
    {
        $param = Request::param();
        $page = isset($param['page']) ? (int)$param['page'] : 1;
        $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
        $showHistory = isset($param['show_history']) ? (bool)$param['show_history'] : false; // 是否显示历史开庭记录

        // 构建查询条件
        $where = [];
        $where[] = ['lc.delete_time', '=', 0];
        // 只查询有开庭时间的案件
        $where[] = ['lc.session_time', '>', 0];

        // 根据参数决定是查询未来的开庭还是所有开庭记录
        if (!$showHistory) {
            // 只查询开庭时间大于等于今天的案件
            $where[] = ['lc.session_time', '>=', strtotime(date('Y-m-d'))];
        }

        // 数据权限过滤逻辑 - 工作台开庭列表放宽权限，显示所有即将开庭的案件
        $userId = $this->getUserId();

        // 1. 检查是否为超级管理员
        $isSuperAdmin = $this->checkSuperAdmin();

        // 2. 获取用户所属部门ID
        $userDepartmentId = $this->getUserDepartmentId();

        // 3. 检查用户是否为律师（通过用户类型判断）
        $userInfo = Db::name('admin')->where('id', $userId)->find();
        $isLawyer = $userInfo && isset($userInfo['user_type']) && ($userInfo['user_type'] == 2); // 2表示外联律师

        // 4. 检查是否为法务中心员工（部门ID为17）
        $isLegalCenterStaff = ($userDepartmentId == 17);

        // 工作台开庭信息列表：放宽权限限制，让用户能看到更多数据
        // 只有在明确指定了主责律师筛选时才进行严格过滤
        if (isset($param['main_lawyer']) && !empty($param['main_lawyer'])) {
            // 如果前端传递了main_lawyer参数，则按该律师筛选
            $where[] = ['lc.main_lawyer', '=', $param['main_lawyer']];
        } elseif (!$isSuperAdmin && !$isLegalCenterStaff && !$isLawyer) {
            // 非管理员、非法务中心、非律师的用户只能看到自己的案件
            if ($userId > 0) {
                $where[] = ['lc.main_lawyer', '=', $userId];
            }
        }
        // 注意：对于律师和法务中心员工，不进行额外的数据权限过滤，让他们能看到所有案件
        
        try {
            // 查询案件开庭时间表
            $list = Db::name('lawcase')
                ->alias('lc')
                ->join('admin a1', 'lc.main_lawyer = a1.id', 'LEFT')
                ->join('admin a2', 'lc.secondary_lawyer = a2.id', 'LEFT')
                ->join('court lcrt', 'lc.court_id = lcrt.id', 'LEFT')
                ->join('lawcase_party lcp', 'lcp.case_id = lc.id AND lcp.is_client = 1', 'LEFT')
                ->join('party p', 'lcp.party_id = p.id', 'LEFT')
                ->field('lc.id, lc.case_code, lc.case_type, lc.stage, lc.status, lc.entrust_date, lc.session_time, lc.session_court_id, lc.create_time, lc.update_time, a1.name as main_lawyer_name, a2.name as secondary_lawyer_name, lcrt.name as court_name')
                ->where($where)
                ->page($page, $limit)
                ->order('lc.session_time', 'asc')
                ->select()
                ->each(function($item) {
                    // 格式化时间
                    $item['create_time'] = $item['create_time'] ? $item['create_time'] : '';
                    $item['update_time'] = $item['update_time'] ? $item['update_time'] : '';
                    $item['entrust_date'] = $item['entrust_date'] ? date('Y-m-d', strtotime($item['entrust_date'])) : '';
                    $item['session_time'] = $item['session_time'] ? date('Y-m-d H:i', $item['session_time']) : '';
                    
                    // 诉讼地位名称映射
                    $relationshipNames = [
                        '1' => '原告',
                        '2' => '被告',
                        '3' => '第三人'
                    ];
                    
                    // 获取委托人信息
                    $clients = Db::name('lawcase_party')
                        ->alias('lp')
                        ->join('party p', 'lp.party_id = p.id', 'LEFT')
                        ->where([
                            ['lp.case_id', '=', $item['id']],
                            ['lp.is_client', '=', 1],
                            ['lp.delete_time', '=', 0]
                        ])
                        ->field('p.name, lp.relationship')
                        ->select();
                    
                    // 处理委托人信息，添加诉讼地位
                    $clientInfos = [];
                    // 确保结果是数组格式
                    if (is_object($clients)) {
                        $clients = $clients->toArray();
                    } elseif (!is_array($clients)) {
                        $clients = [];
                    }
                    foreach ($clients as $client) {
                        $relationshipKey = (string)$client['relationship'];
                        $relationshipName = isset($relationshipNames[$relationshipKey]) ? $relationshipNames[$relationshipKey] : '未知';
                        $clientInfos[] = $client['name'] . '（' . $relationshipName . '）';
                    }
                    $item['client_info'] = implode('，', $clientInfos);
                        
                    // 获取对方当事人信息
                    $opponents = Db::name('lawcase_party')
                        ->alias('lp')
                        ->join('party p', 'lp.party_id = p.id', 'LEFT')
                        ->where([
                            ['lp.case_id', '=', $item['id']],
                            ['lp.is_client', '=', 2],
                            ['lp.delete_time', '=', 0]
                        ])
                        ->field('p.name, lp.relationship')
                        ->select();
                    
                    // 处理对方当事人信息，添加诉讼地位
                    $opponentInfos = [];
                    // 确保结果是数组格式
                    if (is_object($opponents)) {
                        $opponents = $opponents->toArray();
                    } elseif (!is_array($opponents)) {
                        $opponents = [];
                    }
                    foreach ($opponents as $opponent) {
                        $relationshipKey = (string)$opponent['relationship'];
                        $relationshipName = isset($relationshipNames[$relationshipKey]) ? $relationshipNames[$relationshipKey] : '未知';
                        $opponentInfos[] = $opponent['name'] . '（' . $relationshipName . '）';
                    }
                    $item['opponent_info'] = implode('，', $opponentInfos);
                        
                    // 获取开庭法庭名称
                    if ($item['session_court_id']) {
                        // 这里可以根据session_court_id获取具体法庭名称
                        // 假设当前没有专门的法庭表，暂时不处理
                        $item['session_court_name'] = '第' . $item['session_court_id'] . '法庭';
                    } else {
                        $item['session_court_name'] = '';
                    }
                    
                    return $item;
                });
            
            $count = Db::name('lawcase')
                ->alias('lc')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'total' => $count,
                'timestamp' => time()
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取开庭案件列表失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 案件挂起/取消挂起操作
     * @return 	hink\response\Json
     */
    public function suspend()
    {
        try {
            // 获取请求参数
            $param = Request::param();
            $caseId = isset($param['id']) ? intval($param['id']) : 0;
            $status = isset($param['status']) ? intval($param['status']) : 0;
            
            // 参数验证
            if ($caseId <= 0) {
                return json(['code' => 400, 'msg' => '案件ID不能为空']);
            }
            
            if (!in_array($status, [0, 1])) {
                return json(['code' => 400, 'msg' => '状态值无效，只能是0或1']);
            }
            
            // 检查案件是否存在
            $caseInfo = Db::name('lawcase')->where('id', $caseId)->where('delete_time', 0)->find();
            if (!$caseInfo) {
                return json(['code' => 404, 'msg' => '案件不存在']);
            }
            
            // 检查权限（与其他操作保持一致）
            $userId = $this->getUserId();
            $userDepartmentId = $this->getUserDepartmentId();
            $userInfo = Db::name('admin')->where('id', $userId)->find();
            
            // 判断是否为律师
            $isExternalLawyer = $userInfo && isset($userInfo['user_type']) && ($userInfo['user_type'] == 2);
            $hasLawyerLink = $userInfo && isset($userInfo['lawyer_id']) && ($userInfo['lawyer_id'] > 0);
            $isInLawyerTable = Db::name('lawyer')->where('admin_id', $userId)->count() > 0;
            $isLawFirmDept = false;
            if ($userDepartmentId > 0) {
                $deptName = Db::name('department')->where('id', $userDepartmentId)->value('title');
                $isLawFirmDept = $deptName && (strpos($deptName, '律师事务所') !== false);
            }
            $isLawyer = $isExternalLawyer || $hasLawyerLink || $isInLawyerTable || $isLawFirmDept;
            
            // 检查是否为法务中心员工
            $isLegalCenterStaff = ($userDepartmentId == 17);
            
            // 检查是否为超级管理员
            $isSuperAdmin = !$isLawyer && $this->checkSuperAdmin();
            
            // 权限验证：只有案件的主办律师、管家、出庭律师、超级管理员和法务中心员工可以操作
            $hasPermission = $isSuperAdmin || $isLegalCenterStaff || 
                            $caseInfo['main_lawyer'] == $userId || 
                            $caseInfo['secondary_lawyer'] == $userId || 
                            $caseInfo['session_lawyer'] == $userId;
            
            if (!$hasPermission) {
                return json(['code' => 403, 'msg' => '权限不足，无法操作此案件']);
            }
            
            // 更新案件挂起状态
            $updateResult = Db::name('lawcase')
                ->where('id', $caseId)
                ->update([
                    'is_suspended' => $status,
                    'update_time' => time()
                ]);
            
            if ($updateResult) {
                // 记录操作日志
                Log::record('案件ID: ' . $caseId . ' ' . ($status == 1 ? '挂起' : '取消挂起') . ' 操作成功，操作用户: ' . $userId);
                
                // 创建案件进度记录
                try {
                    $progressData = [
                        'case_id' => $caseId,
                        'event_type' => '其他',
                        'event_time' => date('Y-m-d'),
                        'content' => $status == 1 ? '案件已挂起' : '案件已取消挂起',
                        'operator' => $userId,
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    Db::name('lawcase_progress')->insert($progressData);
                    Log::info('案件挂起操作进度记录已创建', ['case_id' => $caseId, 'status' => $status]);
                } catch (\Exception $e) {
                    // 记录错误日志，但不影响主流程
                    Log::error('创建案件挂起操作进度记录失败: ' . $e->getMessage());
                }
                
                return json(['code' => 0, 'msg' => '操作成功']);
            } else {
                return json(['code' => 500, 'msg' => '更新状态失败']);
            }
        } catch (\Exception $e) {
            Log::error('案件挂起/取消挂起操作失败: ' . $e->getMessage());
            return json(['code' => 500, 'msg' => '操作失败: ' . $e->getMessage()]);
        }
    }

}